package cn.lysoy.demo.dataPoolTest;

import org.apache.commons.dbcp2.BasicDataSource;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.Properties;

/**
 * 简易数据库连接池
 * @author 宋杨
 * @email s2295938761@163.com
 * @phone 15216839375
 * @date 2022/9/1
 */
public class MyDatasource {
    //构造方法私有化
    private MyDatasource() {
        init();//在构造方法中初始化连接池
    }
    //提供静态的可以获取本类对象的方法。
    public synchronized static BasicDataSource getDatasource() {
        if(DATASOURCE==null)
            new MyDatasource();
        return DATASOURCE;
    };

    //创建连接池BasicDataSource
    private static BasicDataSource DATASOURCE = null;

    //成员属性
    //数据库连接属性
    private static String driverClass;
    private static String userName;
    private static String url;
    private static String password;
    //初始连接数量
    private static int initCount = 5;
    //最小连接数量
    private static int minCount = 5;
    //最大连接数量
    private static int maxCount = 15;

    //成员属性初始化
    static {
        Properties properties = new Properties();
        try {
            properties.load(MyDatasource.class.getClassLoader().getResourceAsStream("pool/db.properties"));
            driverClass = properties.getProperty("jdbc.driverclass");
            url  = properties.getProperty("jdbc.url");
            userName = properties.getProperty("jdbc.username");
            password = properties.getProperty("jdbc.password");
            try {
                initCount = new Integer(properties.getProperty("jdbc.initCount"));
            } catch (NumberFormatException e) {
                System.out.println("initCount使用默认值："+initCount);
            }
            try {
                minCount = new Integer(properties.getProperty("jdbc.minCount"));
            } catch (NumberFormatException e) {
                System.out.println("minCount使用默认值："+minCount);
            }
            try {
                maxCount = new Integer(properties.getProperty("jdbc.maxCount"));
            } catch (NumberFormatException e) {
                System.out.println("maxCount使用默认值："+maxCount);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 初始化连接池
     */
    private void init() {
        DATASOURCE = new BasicDataSource();
        DATASOURCE.setDriverClassName(driverClass);
        DATASOURCE.setUrl(url);
        DATASOURCE.setUsername(userName);
        DATASOURCE.setPassword(password);
        DATASOURCE.setInitialSize(initCount);
        DATASOURCE.setMinIdle(minCount);
        DATASOURCE.setMaxIdle(maxCount);
    }
}
